using System;
using System.Text;

namespace MiniJson
{
    public static class JsonReader
    {
        /// <summary>
        /// Parses the string json into a value
        /// </summary>
        /// <param name="json">A JSON string.</param>
        /// <returns>An List&lt;object&gt;, a Dictionary&lt;string, object&gt;, a double, an integer,a string, null, true, or false</returns>
        public static JsonValue Parse(string json)
        {

            if (json == null)
            {
                return null;
            }

            if (String.IsNullOrEmpty(json.Trim()))
            {
                return null;
            }


            return Parser.Parse(json);
        }

        sealed class Parser : IDisposable
        {
            const string WORD_BREAK = "{}[],:\"";

            public static bool IsWordBreak(char c)
            {
                return Char.IsWhiteSpace(c) || WORD_BREAK.IndexOf(c) != -1;
            }

            enum TOKEN
            {
                NONE,
                CURLY_OPEN,
                CURLY_CLOSE,
                SQUARED_OPEN,
                SQUARED_CLOSE,
                COLON,
                COMMA,
                STRING,
                NUMBER,
                TRUE,
                FALSE,
                NULL
            };

            StringBuilder json;
            int jsonIndex = 0;

            Parser(string jsonString)
            {
                json = new StringBuilder(jsonString);
            }

            public static JsonValue Parse(string jsonString)
            {
                using (var instance = new Parser(jsonString))
                {
                    return instance.ParseValue();
                }
            }

            public void Dispose()
            {
                json = null;
            }

            JsonValue ParseObject()
            {
                JsonValue table = JsonValue.Object();

                // ditch opening brace
                //json.Read();
                jsonIndex++;
                // {
                while (true)
                {
                    switch (NextToken)
                    {
                        case TOKEN.NONE:
                            return null;
                        case TOKEN.COMMA:
                            continue;
                        case TOKEN.CURLY_CLOSE:
                            return table;
                        default:
                            // name
                            string name = ParseString();
                            if (name == null)
                            {
                                return null;
                            }

                            // :
                            if (NextToken != TOKEN.COLON)
                            {
                                return null;
                            }
                            // ditch the colon
                            //json.Read();
                            jsonIndex++;

                            // value
                            table.Add(name, ParseValue());
                            break;
                    }
                }
            }

            JsonValue ParseArray()
            {
                JsonValue array = JsonValue.Array();

                // ditch opening bracket
                //json.Read();
                jsonIndex++;
                int i = 0;

                // [
                var parsing = true;
                while (parsing)
                {
                    TOKEN nextToken = NextToken;

                    switch (nextToken)
                    {
                        case TOKEN.NONE:
                            i = 0;
                            return null;
                        case TOKEN.COMMA:
                            i = 0;
                            continue;
                        case TOKEN.SQUARED_CLOSE:
                            i = 0;
                            parsing = false;
                            break;
                        default:
                            i++;
                            JsonValue value = ParseByToken(nextToken);
                            if (i > 100)
                            {
                                return null;
                            }

                            array.Add(value);
                            break;
                    }
                }

                return array;
            }

            JsonValue ParseValue()
            {
                TOKEN nextToken = NextToken;
                return ParseByToken(nextToken);
            }

            JsonValue ParseByToken(TOKEN token)
            {
                switch (token)
                {
                    case TOKEN.STRING:
                        return new JsonValue(ParseString());
                    case TOKEN.NUMBER:
                        return new JsonValue(ParseNumber());
                    case TOKEN.CURLY_OPEN:
                        return ParseObject();
                    case TOKEN.SQUARED_OPEN:
                        return ParseArray();
                    case TOKEN.TRUE:
                        return new JsonValue(true);
                    case TOKEN.FALSE:
                        return new JsonValue(false);
                    case TOKEN.NULL:
                        return JsonNull.GetInstance();
                    default:
                        return null;
                }
            }

            string ParseString()
            {
                StringBuilder s = new StringBuilder();
                char c;

                // ditch opening quote
                //json.Read();
                jsonIndex++;
                bool parsing = true;
                while (parsing)
                {

                    if (jsonIndex>=json.Length)
                    {
                        parsing = false;
                        break;
                    }

                    c = NextChar;
                    switch (c)
                    {
                        case '"':
                            parsing = false;
                            break;
                        case '\\':
                            if (jsonIndex >= json.Length)
                            {
                                parsing = false;
                                break;
                            }
                            s.Append(c);
                            c = NextChar;
                            s.Append(c);
                            break;
                        default:
                            s.Append(c);
                            break;
                    }
                }

                return s.ToString();
            }

            object ParseNumber()
            {
                string number = NextWord;

                if (number.IndexOf('.') == -1)
                {

                    long parsedInt;
                    Int64.TryParse(number, out parsedInt);
                    return parsedInt;
                }

                double parsedDouble;
                Double.TryParse(number, out parsedDouble);
                return parsedDouble;
            }

            void EatWhitespace()
            {
                while (Char.IsWhiteSpace(PeekChar))
                {
                    //json.Read();
                    jsonIndex++;
                    if (jsonIndex >= json.Length)
                    {
                        break;
                    }
                }
            }

            char PeekChar
            {
                get
                {
                    if (jsonIndex >= json.Length)
                        return Convert.ToChar(-1);
                    return Convert.ToChar(json[jsonIndex]);
                }
            }

            char NextChar
            {
                get
                {
                    if (jsonIndex >= json.Length)
                    {
                        return Convert.ToChar(-1);
                    }
                    char v = Convert.ToChar(json[jsonIndex]);
                    jsonIndex++;
                    return v;
                }
            }

            string NextWord
            {
                get
                {
                    StringBuilder word = new StringBuilder();

                    while (!IsWordBreak(PeekChar))
                    {
                        word.Append(NextChar);

                        if (jsonIndex >= json.Length)
                        {
                            break;
                        }
                    }

                    return word.ToString();
                }
            }

            TOKEN NextToken
            {
                get
                {
                    EatWhitespace();

                    if (jsonIndex >= json.Length)
                    {
                        return TOKEN.NONE;
                    }

                    switch (PeekChar)
                    {
                        case '{':
                            return TOKEN.CURLY_OPEN;
                        case '}':
                            jsonIndex++;
                            return TOKEN.CURLY_CLOSE;
                        case '[':
                            return TOKEN.SQUARED_OPEN;
                        case ']':
                            jsonIndex++;
                            return TOKEN.SQUARED_CLOSE;
                        case ',':
                            jsonIndex++;
                            return TOKEN.COMMA;
                        case '"':
                            return TOKEN.STRING;
                        case ':':
                            return TOKEN.COLON;
                        case '0':
                        case '1':
                        case '2':
                        case '3':
                        case '4':
                        case '5':
                        case '6':
                        case '7':
                        case '8':
                        case '9':
                        case '-':
                            return TOKEN.NUMBER;
                    }

                    switch (NextWord)
                    {
                        case "false":
                            return TOKEN.FALSE;
                        case "true":
                            return TOKEN.TRUE;
                        case "null":
                            return TOKEN.NULL;
                    }

                    return TOKEN.NONE;
                }
            }
        }


    }
}